<?php
/**
 * @file upgrade.php $
 * @author LiangJian (liangjian@haibao.com) $
 * @date 2015年8月31日 下午4:11:34 $
 * @brief 升级提示 $
 */
namespace haibao\app\data;

use \haibao\frame\data\query\Condition;

class AppUpgrade extends \haibao\app\data\BaseMysql{

    public function __construct(){
        parent::__construct('\haibao\app\model\data\AppUpgrade');
    }
    
    public function getUpgradeById($id){
        return $this->getOneById($id);
    }
    
    /**
     * 根据手机类型查询最高版本APP应用
     */
    public function getUpgradeByAppType($appType){
        $cache = new \haibao\app\cache\Upgrade();
        $upGradeList = $cache->getHighestVersion($appType);
        if(!$upGradeList){
        	$upGradeList = array();
            $result = $this->query('select Title,AppType,Content,Version,Url from AppUpgrade where Version=(select max(`Version`) as highest_version from AppUpgrade where AppType=%s and Status=1 limit 1) and  AppType=%s and Status=1  limit 1', array($appType,$appType));
            while($result->fetch_assoc()){
            	$upGradeList['Title'] = $result->getData('Title');
            	$upGradeList['AppType'] = $result->getData('AppType');
            	$upGradeList['Content'] = $result->getData('Content');
            	$upGradeList['Version'] = $result->getData('Version');
            	$upGradeList['Url'] = $result->getData('Url');
            	break;
            }
            
            $cache->setHighestVersion($appType, $upGradeList);
        }
        return $upGradeList;
    }
    
    /**
     * @param \haibao\app\model\data\AppUpgrade $model
     */
    public function saveUpgrade($model){
        if($model->Id){
            $this->updateById($model->Id, array(
                \haibao\app\model\filter\AppUpgrade::CONDITION_FIELD_NAME_TITLE => $model->Title,
                \haibao\app\model\filter\AppUpgrade::CONDITION_FIELD_NAME_APP_TYPE => $model->AppType,
                \haibao\app\model\filter\AppUpgrade::CONDITION_FIELD_NAME_CONTENT => $model->Content,
                \haibao\app\model\filter\AppUpgrade::CONDITION_FIELD_NAME_VERSION => $model->Version,
                \haibao\app\model\filter\AppUpgrade::CONDITION_FIELD_NAME_URL => $model->Url,
                \haibao\app\model\filter\AppUpgrade::CONDITION_FIELD_NAME_STATUS => $model->Status,
            ));
        }else{
            $this->add($model);
        }
        $cache = new \haibao\app\cache\Upgrade();
        $cache->deleteHighestVersion($model->AppType);
    }
    
    public function updateStatusById($id, $status = \haibao\app\model\data\AppUpgrade::STATUS_DISABLE){
        $this->updateById($id, array(
            \haibao\app\model\filter\AppUpgrade::CONDITION_FIELD_NAME_STATUS => $status,
        ));
        
        $model = $this->getOneById($id);
        $cache = new \haibao\app\cache\Upgrade();
        $cache->deleteHighestVersion($model->AppType);
    }
}